package com.zdb.algorithm.binarysearchnorecursion;

public class BinarySearchNoRecursionDemo {

    public static void main(String[] args) {
        
        int arr[] = {1, 3, 8, 61, 100, 500,1000};

        int index = binarySearch(arr, 1000);
        System.out.println("index=" + index);
    }

    /**
     * 非递归二分查找
     * @param arr 升序数组
     * @param target 待查找的数字
     * @return 返回待查找数字下标，找不到返回-1
     */
    public static int binarySearch(int[] arr, int target) {

        int left = 0;
        int right = arr.length - 1;

        while(left <= right) {

            int mid = (left + right) / 2;

            if(arr[mid] == target) {
                return mid;
            } else if(arr[mid] > target ) {
                // 向左边查找
                right = mid - 1;
            } else {
                // 向右边查找
                left = mid + 1;
            }


        }

        return -1;
    }
}
